package org.zyl.util.md5;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import org.zyl.util.validate.ValidateUtil;

public class SignatureUtil {
	public static String getParamStr(TreeMap<String, Object> param) {
		StringBuffer sb = new StringBuffer();
		Iterator<String> i = param.keySet().iterator();
		while (i.hasNext()) {
			String key = i.next();
			if ("sign".equals(key)) {
				continue;
			}
			sb.append(key);
			sb.append("=");
			sb.append(param.get(key)+"");
			sb.append("&");
		}
		String result = sb.toString();
		if (!ValidateUtil.isNotBlank(result)) {
			return null;
		}
		
		return result.substring(0,result.length()-1);
	}
	public static String getParamStr(Map<String, Object> param) {
		StringBuffer sb = new StringBuffer();
		Object[] keys = param.keySet().toArray();
		Arrays.sort(keys);
		
		for (Object obj : keys) {
			if ("sign".equals(obj)) {
				continue;
			}
			
			sb.append(obj);
			sb.append("=");
			sb.append(param.get(obj)+"");
			sb.append("&");
		}
		
		String result = sb.toString();
		if (!ValidateUtil.isNotBlank(result)) {
			return null;
		}
		
		return result.substring(0,result.length()-1);
	}
	
	public static String getMd5Signature(String content,String key) {
		if (!ValidateUtil.isNotBlank(content)||!ValidateUtil.isNotBlank(key)) {
			return null;
		}
		try {
			byte[] b = (content+key).getBytes("UTF-8");
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.reset();
			md.update(b);
			byte[] hash = md.digest();
			StringBuffer outStrBuf = new StringBuffer(32);
			for (int i = 0; i < hash.length; i++) {
				int v = hash[i] & 0xFF;
				if (v < 16) {
					outStrBuf.append('0');
				}
				outStrBuf.append(Integer.toString(v, 16).toLowerCase());
			}
			return outStrBuf.toString().toUpperCase();
		} catch (Exception e) {
			System.out.println("----- getMd5Signature签名错误");
			e.printStackTrace();
		}
		return null;
	}
	
}